package services

import (
	"goetl/models"

	//"github.com/astaxie/beego/logs"
)
import "github.com/astaxie/beego/orm"
import "goetl/comps"
import (
	"time"
)

//配置操作相关
type configurationService struct{}

/*查询工程列表*/
func (this *configurationService) FindProjects() (err error, resultProjects []*models.Project) {

	o := orm.NewOrm()

	project := new(models.Project)
	qs := o.QueryTable(project)
	_, err = qs.Filter("Deleted", 0).All(&resultProjects)

	//_, err = o.LoadRelated(&resultProjects, "ProjectVersions")
	return

}

/*查询指定工程的版本列表*/
func (this *configurationService) FindProjectVersionsByProject(projectId string) (err error, resultProjectVersions []*models.ProjectVersion) {

	o := orm.NewOrm()
	projectVersion := new(models.ProjectVersion)
	qs := o.QueryTable(projectVersion)
	_, err = qs.Filter("Deleted", 0).Filter("ProjectId", projectId).RelatedSel().All(&resultProjectVersions)

	return
}

/*查询指定工程版本的流程列表*/
func (this *configurationService) FindFlowsInProject(projectVersionId string, test int32) (err error, resultFlows []*models.Flow) {

	o := orm.NewOrm()
	flow := new(models.Flow)
	qs := o.QueryTable(flow)
	_, err = qs.Filter("Deleted", 0).Filter("Test", test).Filter("ProjectVersionId", projectVersionId).All(&resultFlows)

	return
}

/*查询指定工程版本的模型列表*/
func (this *configurationService) FindModelsInProject(projectVersionId string) (err error, resultModels []*models.Model) {

	o := orm.NewOrm()
	model := new(models.Model)
	qs := o.QueryTable(model)
	_, err = qs.Filter("Deleted", 0).Filter("ProjectVersionId", projectVersionId).All(&resultModels)

	return
}

/*查询指定工程版本的资源列表*/
func (this *configurationService) FindResourcesInProject(projectVersionId string) (err error, resultResources []*models.Resource) {

	o := orm.NewOrm()
	resource := new(models.Resource)
	qs := o.QueryTable(resource)
	_, err = qs.Filter("Deleted", 0).Filter("ProjectVersionId", projectVersionId).All(&resultResources)

	return
}

/*查询指定工程版本的依赖列表*/
func (this *configurationService) FindProjectDependencies(projectVersionId string) (err error, result []*models.ProjectVersionDependency) {

	o := orm.NewOrm()
	p := new(models.ProjectVersionDependency)
	qs := o.QueryTable(p)
	_, err = qs.Filter("ProjectVersionId", projectVersionId).All(&result)
	for i := range result {
		err, target := this.FindProjectVersion(result[i].TargetProjectVersionId.Id)
		o.LoadRelated(&target, "ProjectId")
		if err == nil {
			result[i].TargetProjectVersionId = &target
		}
	}
	return
}

/*查询指定工程版本*/
func (this *configurationService) FindProjectVersion(projectVersionId string) (err error, result models.ProjectVersion) {

	o := orm.NewOrm()
	p := new(models.ProjectVersion)
	qs := o.QueryTable(p)
	err = qs.Filter("Id", projectVersionId).One(&result)
	return
}

/*查询指定资源*/
func (this *configurationService) FindResource(id string) (err error, result models.Resource) {
	o := orm.NewOrm()
	p := new(models.Resource)
	qs := o.QueryTable(p)
	err = qs.Filter("Id", id).One(&result)
	return
}

/*查询指定资源的定义*/
func (this *configurationService) FindResourceDefinition(id string) (result map[string]interface{}) {
	//l := logs.GetLogger()
	//l.Println(comps.Resources)
	result = (comps.Resources[id]).(map[string]interface{})

	return
}

/*查询指定资源的设定*/
func (this *configurationService) FindResourceSettting(resourceId string) (err error, result []models.ResourceSetting) {
	o := orm.NewOrm()
	_, err = o.Raw("select * from goetl_resource_setting where resource_id=?", resourceId).QueryRows(&result)

	return
}

/*保存资源的设定*/
func (this *configurationService) SaveResourceSettings(data []models.SaveResourceSetting, user models.User) (err error) {

	o := orm.NewOrm()

	for i := range data {
		var num int32
		err = o.Raw("select count(1) from goetl_resource_setting where resource_id=? and name =? ", data[i].ResourceId, data[i].Name).QueryRow(&num)
		if err == nil {
			if num > 0 {
				_, err = o.Raw("update  goetl_resource_setting  set value=?,last_update_by=? ,last_update_time=?  where resource_id=? and name =? ", data[i].Value, user.LoginId, time.Now(), data[i].ResourceId, data[i].Name).Exec()
			} else {
				_, err = o.Raw(" insert into goetl_resource_setting (resource_id, name,value,create_time,create_by) values(?,?,?,?,?)  ", data[i].ResourceId, data[i].Name, data[i].Value, time.Now(), user.LoginId).Exec()
			}
		}
	}
	return

}

/*查询模型*/
func (this *configurationService) FindModel(id string) (err error, result models.Model) {
	o := orm.NewOrm()
	p := new(models.Model)
	qs := o.QueryTable(p)
	err = qs.Filter("Id", id).One(&result)

	if err == nil {
		_, err = o.LoadRelated(&result, "ModelEntitys")

		if err == nil {

			for i := range result.ModelEntitys {
				entity := result.ModelEntitys[i]
				_, err = o.LoadRelated(entity, "ModelAttributes", true, 1000, 0, "attribute_order")
			}
		}

	}
	return
}

/*查询流程*/
func (this *configurationService) FindFlow(id string) (err error, result models.Flow) {
	o := orm.NewOrm()
	p := new(models.Flow)
	qs := o.QueryTable(p)
	err = qs.Filter("Id", id).One(&result)

	if err == nil {
		_, err = o.LoadRelated(&result, "FlowSteps")
		for i := range result.FlowSteps {
			step := result.FlowSteps[i]
			_, err = o.LoadRelated(step, "ComponentId")
			if comps.ComponentUis[step.ComponentId.Type] != nil {
				step.Ui = comps.ComponentUis[step.ComponentId.Type].(map[string]interface{})
			} else {
				step.Ui = make(map[string]interface{})
			}
		}
		_, err = o.LoadRelated(&result, "ProjectVersionId")
	}
	return
}

/*查询流程步骤连接*/
func (this *configurationService) FindFlowStepLinks(flowId string) (err error, result []*models.FlowStepLink) {
	o := orm.NewOrm()

	_, err = o.Raw("SELECT distinct l.* FROM goetl_flow_step_link l , goetl_flow_step sl where ( l.source_step_id =sl.id or  l.target_step_id =sl.id ) and sl.flow_id =?", flowId).QueryRows(&result)
	return
}

/*根据ID查询控件*/
func (this *configurationService) FindComponent(componentId string, readRelations bool) (err error, result models.Component) {
	o := orm.NewOrm()
	p := new(models.Component)
	qs := o.QueryTable(p)
	err = qs.Filter("Id", componentId).One(&result)

	if err == nil {
		componentDefinition := (comps.Components[result.Type].(map[string]interface{}))
		result.Type = componentDefinition["name"].(string)
		result.ComponentDefinition = componentDefinition
	}
	if err == nil && readRelations {
		//_, err = o.LoadRelated(&result, "ResourceId")//资源ID
		//_, err = o.LoadRelated(&result, "InputModelId")
		//_, err = o.LoadRelated(&result, "OutputModelId")

		_, err = o.LoadRelated(&result, "ComponentAttributeSettings")
		_, err = o.LoadRelated(&result, "ComponentEntitySettings")
		_, err = o.LoadRelated(&result, "ComponentSettings") //控件属性值

		//控件定义设定
		flowSettingsCount := 0
		settings := result.ComponentDefinition["settings"].([]map[string]interface{})
		//检查是否有流程下拉框
		for i := range settings {
			if settings[i]["type"] != nil && settings[i]["type"].(string) == "flow" {
				flowSettingsCount++
			}
		}
		//输出流程下拉框
		if flowSettingsCount > 0 {
			_, result.Flows = this.FindFlowsInProject(result.ProjectVersionId.Id, 0)
		}

		if result.ComponentDefinition["inputMessageType"] == "entity" || (result.ComponentDefinition["inputMessageType"] == "any" && result.ComponentDefinition["showInputModel"] == "true") || result.ComponentDefinition["outputMessageType"] == "entity" || (result.ComponentDefinition["outputMessageType"] == "any" && result.ComponentDefinition["showOutputModel"] == "true") {
			_, err = o.Raw("SELECT distinct m.* FROM goetl_model m left join goetl_project_version_dependency d on  d.  target_project_version_id=m.project_version_id   where m.deleted=0 and ( m.project_version_id =? or    d. project_version_id=?)", result.ProjectVersionId.Id, result.ProjectVersionId.Id).QueryRows(&result.DropDownModels)
		}

		//控件属性值map
		compSettingsMap := make(map[string]string)
		for i := range result.ComponentSettings {
			compSettingsMap[result.ComponentSettings[i].Name] = result.ComponentSettings[i].Value
		}
		result.ComponentSettingsMap = compSettingsMap

	}
	return
}

func (this *configurationService) FindFirstFolderWithName(name string, foldertype string) (err error, result models.Folder) {
	o := orm.NewOrm()
	p := new(models.Folder)
	qs := o.QueryTable(p)
	err = qs.Filter("name", name).Filter("Deleted", 0).One(&result)

	return
}

func (this *configurationService) SaveFolder(folder models.Folder) (err error) {
	o := orm.NewOrm()

	_, err = o.InsertOrUpdate(folder)

	return
}
func (this *configurationService) SaveAgent(agent models.Agent) (err error) {
	o := orm.NewOrm()

	_, err = o.InsertOrUpdate(agent)

	return
}
